//
//  AssistantViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/4/28.
//

#import "AssistantViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "AssistantRightTableViewCell.h"
#import "AssistantLeftTableViewCell.h"
#import "MessageModel.h"

@interface AssistantViewController ()<QInputBarViewDelegate,QInputBarViewDataSource,InputBoardDataSource,InputBoardDelegate,UITableViewDelegate,UITableViewDataSource>

@end

@implementation AssistantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.zx_navTitle = SQNSLocalString(@"小觅");
    // Do any additional setup after loading the view.
}

- (void)SQ_UIViewForSelfView{
    UIImageView * bgImage = [[UIImageView alloc]init];
    bgImage.image = SQGetImage(@"助手");
    bgImage.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:bgImage];
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.view);
        make.size.mas_equalTo(SCREEN_HEIGHT*1.25);
    }];
    self.view.clipsToBounds  = YES;
    
    CABasicAnimation * rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI * 2.0 ];
    rotationAnimation.duration = 600;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.removedOnCompletion = NO;
    [bgImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    self.showEmpty = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(TopHeight, 0, FootHeight+60, 0));
    }];
    [self SQ_tableViewAddRefresh];
    [self SQ_Header];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewWillBeginDragging:)];
    [self.tableView addGestureRecognizer:tap];
    [self.keyBoardManager addBottomInputBarView:self.putView belowViewController:NO];
    [self.keyBoardManager bindTextView:self.putView.inputTextView];
}
//点击了系统键盘的发送按钮
- (void)inputBarView:(QInputBarView *)inputBarView onKeyboardSendClick:(NSString *)inputNormalText {
    if (![inputNormalText isNotEmpty]) {
        return;
    }
    UserModel * usermodel = [UserModel share];
    MessageModel * model  = [MessageModel new]; //创建我发的消息
    model.portrait = usermodel.portrait;
    model.name = usermodel.name;
    model.content = inputNormalText;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:YES];
    
    MessageModel * model2  = [MessageModel new];//创建假的回复消息
    model2.name = SQNSLocalString(@"小觅");
    model2.sendType = YES; //发送对象
    model2.type = 1; //类型为1
    model2.content = SQNSLocalString(@"小觅正在思考中...");
    [self.jsonArray addObject:model2];
    [self insertAndScrollToBottom:model2 needClearInputText:YES];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:inputNormalText forKey:@"content"];
    [HttpTool post:Url34 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        MessageModel * mo = [MessageModel mj_objectWithKeyValues:httpModel.data];
        model2.content = mo.content;
        model2.userId = mo.userId;
        model2.type = 0;
        [self insertAndScrollToBottom:model2 needClearInputText:YES];
        
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        model2.content = SQNSLocalString(@"思考失败,请检查网络或者重新提问!");
        model2.type = 2;
        [self insertAndScrollToBottom:model2 needClearInputText:YES];
    }];
}
- (void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@(self.page) forKey:@"current"];
    [dic setObject:@"20" forKey:@"size"];
    [HttpTool post:Url35 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSDictionary * data = [[NSDictionary alloc]initWithDictionary:httpModel.data];
        NSArray * array = [MessageModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"records"]];
        [self.jsonArray addObjectsFromArray:[MessageModel sortArray:array increase:YES byKey:@"userId"]];
        if (array.count > 0) {
            [self.tableView reloadData];
            [self scrollToBottomAnimated:NO];
            self.page++;
        }
        [self.tableView.mj_header endRefreshing];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)SQ_Foother{
    [self.tableView.mj_footer endRefreshing];
}

#pragma  mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.jsonArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    NSString * Identifier = [NSString stringWithFormat:@"AssistantLeftTableViewCell%ld",(long)indexPath.item];
    if (model.sendType) {
        AssistantLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[AssistantLeftTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        Identifier = [NSString stringWithFormat:@"AssistantRightTableViewCell%ld",(long)indexPath.item];
        AssistantRightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[AssistantRightTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}


//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.keyBoardManager hideAllBoardView];
}
 
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (model.sendType) {
        return  [AssistantLeftTableViewCell FSCellHeightForTableView:tableView indexPath:indexPath cellContentViewWidth:0 bottomOffset:10];
    }
   return  [AssistantRightTableViewCell FSCellHeightForTableView:tableView indexPath:indexPath cellContentViewWidth:0 bottomOffset:10];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJChangePopMenuIfNeeded object:nil];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //用户手动拖动tableview，隐藏所有面板和键盘
    [self.keyBoardManager hideAllBoardView];
}

//添加到array中 + reload和滚到底部。 needClearInputText: 是否需要清空文本框输入的内容
- (void)insertAndScrollToBottom:(MessageModel *)contentModel needClearInputText:(BOOL)needClearInputText {
    if (contentModel ==nil) {
        return;
    }
    //添加到array中
    NSTimeInterval animationDuration = needClearInputText ? [self.putView clearInputTextBySend] : 0;
    //reloadData并滚到底部
    [self reloadDataAndScrollToBottomAnimated:YES animationDelay:animationDuration];
}
//reloadData并滚到底部
- (void)reloadDataAndScrollToBottomAnimated:(BOOL)animated animationDelay:(NSTimeInterval)animationDelay {
     BOOL resultAnimated = animated;
    if (animationDelay == 0){
        //如果textView的文本只有一行，那么清空输入框的时候，不会走onWholeInputViewHeightDidChange回调，也不会重新设置tableView的contentInset。所以就无需延时reloadData
        [self.tableView reloadData];
        [self scrollToBottomAnimated:resultAnimated];
    } else {
        //textView的文本大于一行，那么清空输入框的时候，会重设tableView的contentInset（并且我还是在0.2秒的动画里重设的），如果这时候reloadData，在低性能设备上会出现tableView来回上下移动的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(animationDelay * NSEC_PER_SEC)), dispatch_get_main_queue(),  ^{
            [self.tableView reloadData];
            [self scrollToBottomAnimated:resultAnimated];
        });
    }
}
//滚到底部
-(void)scrollToBottomAnimated:(BOOL)animated {
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}
#pragma mark - InputBoardDelegate
//整个“输入View”的高度发生变化（整个View包含bar和表情栏或者键盘，但是不包含底部安全区高度）
- (void)keyboardManager:(QKeyboardManager *)keyboardManager onWholeInputViewHeightDidChange:(CGFloat)wholeInputViewHeight reason:(WholeInputViewHeightDidChangeReason)reason {
    WS(weakSelf);
    BOOL alreadyAtBottom = [self SQ_alreadyAtBottom:weakSelf.tableView];
    UIEdgeInsets insets = UIEdgeInsetsZero;
    insets.top = 0;
    insets.bottom = wholeInputViewHeight-60;
    //对应聊天界面，随着底部输入框的frame.y的变化，为了保持tableview一直都在输入条的上方，修改tableview的contentInset
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
    if (reason == WholeInputViewHeightDidChangeReasonWillAddToSuperView){ //聊天界面，tableView要滚到底部
        dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToBottomAnimated:NO];
     });
        return;
    }
    if (reason == WholeInputViewHeightDidChangeReasonTextDidSend) {
        //是点击“发送”按钮清空输入框里的多行文字导致的输入栏高度变化
        return;
    }
    if (alreadyAtBottom) {
        //用自己的animations，问题就是会闪屏，尤其是tableview滚在上方时候 闪的越狠；好处是tableview在切换时候很跟手
        [UIView animateWithDuration:keyboardManager.inputBarHeightChangeAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self scrollToBottomAnimated:NO];
        } completion:nil];
    } else {
        [self scrollToBottomAnimated:YES];
    }
}

#pragma mark - QInputBarViewDataSource
//@return 输入条上的UITextView，返回你自定义的UITextView
- (UITextView *)textViewForInputBarView:(QInputBarView *)inputBarView {
    FSTextView *tv = [[FSTextView alloc] init];
    tv.layer.cornerRadius = 4;
    [tv setShowsVerticalScrollIndicator:NO];
    [tv setShowsHorizontalScrollIndicator:NO];
    tv.returnKeyType = UIReturnKeySend;
    tv.placeholder = @"快来跟我说悄悄话吧~";
    tv.placeholderColor = SQColorF5F5F5;
    tv.textColor = UIColor.whiteColor;
    tv.font = FONT_MEDIUM(16);
    return tv;
}
#pragma mark - QInputBarViewDelegate
// 输入框的高度发生了改变（因为输入框里的文字行数变化了），注意这里仅仅是TextView输入框的高度发生了变化的回调；becauseSendText：YES表示是因为调用了clearInputTextBySend去发送文本
- (void)inputBarView:(QInputBarView *)inputBarView inputTextView:(UITextView *)inputTextView heightDidChange:(CGFloat)changeValue becauseSendText:(BOOL)becauseSendText {
    //这里要告知Manager类
    [self.keyBoardManager inputTextViewHeightDidChange:becauseSendText];
}

//点击了“发送”按钮
- (void)onSendButtonSelect:(UIButton *)sender {
    //发送给服务器
    [self inputBarView:self.putView onKeyboardSendClick:[self.putView textViewInputNormalText]];
}
-(BOOL)SQ_alreadyAtBottom:(UITableView*)view{
    if (((NSInteger)view.contentOffset.y) == ((NSInteger)view.contentSize.height + view.adjustedContentInset.bottom - CGRectGetHeight(view.bounds))) {
        return YES;
    }
    return NO;
}


- (void)dealloc{
    DTLog(@"当前im类是否释放");
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.keyBoardManager.viewControllerWillDisappear = NO;
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 避免手势返回的时候输入框往下掉
    self.keyBoardManager.viewControllerWillDisappear = YES;
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;;
}

- (QInputBarView *)putView{
    if (!_putView) {
        _putView = [[QInputBarView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 60)];
        _putView.delegate = self;
        _putView.dataSource = self;
        QInputBarViewConfiguration *config = [QInputBarViewConfiguration defaultInputBarViewConfiguration];
        config.inputBarBackgroundColor = SQHexColor(@"#000000", 0.6);
        config.inputBarBoardColor = SQHexColor(@"#000000", 0.6);
        config.textViewBackgroundColor = SQHexColor(@"#FFFFFF", 0.4);
        config.textColor = UIColor.whiteColor;
        config.voiceButtonHidden = YES;
        config.emotionButtonHidden = YES;
        config.extendButtonHidden = YES;
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 42)];
        [btn addTarget:self action:@selector(onSendButtonSelect:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:SQNSLocalString(@"提问") forState:normal];
        btn.backgroundColor = SQHexColor(@"#FFFFFF", 0.4);
        [btn setTitleColor:UIColor.whiteColor forState:normal];
        btn.titleLabel.font = FONT_MEDIUM(16);
        btn.layer.cornerRadius = 4;
        btn.layer.masksToBounds = YES;
        config.rightSendButton = btn;
        [_putView setupWithConfiguration:config];
//        _putView.inputTextView.textColor = SQColor(@"#333333");
    }
    return _putView;
}
- (QKeyboardManager *)keyBoardManager{
    if (!_keyBoardManager) {
        _keyBoardManager = [[QKeyboardManager alloc]initWithViewController:self];
        _keyBoardManager.dataSource = self;
        _keyBoardManager.delegate = self;
    }
    return _keyBoardManager;
}
@end
